package com.efounder.activity;

/**
 * Created by will on 18-1-8.
 */

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import android.view.View;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.bean.OrderList;
import com.efounder.bean.UpdateCartBadgeEvent;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilemall.R;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.utils.MallRequestUtil;
import com.efounder.view.EFImage;
import com.efounder.view.MallTabBar;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.widget.TabBarNew;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.resmanager.ResFileManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.CART_AMOUNT_URL;
import static com.efounder.utils.MallRequestUtil.ORDER_LIST_URL;


/**
 * Created by wwl on 2018/1/4.
 * 商城首页，tabLayout与viewPager配置
 */
public class MainMallActivity extends AbActivity implements
        TabBarNew.OnCurrentTabChangedListener {
    private String TAG = this.getClass().getSimpleName();
    private List<StubObject> mainMenus; // 主菜单
    private MallTabBar tb;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private AbBottomBar mBottomBar = null;
    /**
     * 当前Tab页面索引
     */
    public int currentTab;
    /**
     * 默认展示页
     */
    private final static int inittab = 0;
    private FragmentManager fm;
    private BaseFragment willShowFragment;
    private BaseFragment willHideFragment;
    public BaseFragment[] cachedFragments; // 缓存主菜单对应的Fragments

    private int currentIndex = 0;

    public static void start(Context context) {
        Intent starter = new Intent(context, MainMallActivity.class);
//        starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setAbContentView(R.layout.activity_main);
//        initBadge();
        fm = getSupportFragmentManager();
        initView();
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
//        initBadge();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveCartBadgeEvent(UpdateCartBadgeEvent event) {
//        initBadge();
    }

    private void initView() {
        //加载配置文件
        if (mainMenus == null) {
//            mainMenus = CommonMethodUtil.getTab_Menu_FromXml();
            mainMenus = getMain_Menu_FromXml();
        }
        cachedFragments = new BaseFragment[mainMenus.size()];
//        makeMainMenu();
        currentTab = inittab;
        willHideFragment = willShowFragment;
        willShowFragment = initAndCacheFragment(currentTab);
        showFragment(willShowFragment);
    }

    /**
     * 加载完主菜单之后调用, 生存主菜单布局
     */
    private void makeMainMenu() {
        if (mainMenus == null) {
            Toast.makeText(this, R.string.mail_get_data_fail_again, Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }
//        loadBottomBar(mainMenus);
    }

    public List<StubObject> getMain_Menu_FromXml() {
        File file = new File(ResFileManager.PACKAGE_DIR + "/"
                + "Mall_Menu.xml");
        mainMenus = Registry.getRegEntryList("MallRoot");

        MenuGnqxUtil.handleGNQX(mainMenus);//处理功能权限
        return mainMenus;
    }

    private void loadBottomBar(List<StubObject> espMenuList) {
        mBottomBar = this.getBottomBar();
        mBottomBar.removeAllViews();
        mBottomBar.setVisibility(View.VISIBLE);
        tb = new MallTabBar(this, espMenuList);
        mBottomBar.addView(tb);
        tb.setOnCurrentTabChangedListener(this);
        //旧方式加载fragment yqs
        currentTab = inittab;
        willHideFragment = willShowFragment;
        willShowFragment = initAndCacheFragment(currentTab);
        showFragment(willShowFragment);
    }

    /**
     * 创建并且缓存Fragment
     *
     * @param index
     */
    private BaseFragment initAndCacheFragment(int index) {
        BaseFragment frag = null;
        StubObject mainMenuItem = mainMenus.get(index);

        // frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
        AbFragmentManager ab = new AbFragmentManager(this);
        // 根据viewtype的类型得到
        frag = ab.getFragment(mainMenuItem);

        frag.setBadgeType("" + index);
        cachedFragments[index] = frag; // 缓存
        frag.setAlone(false);

        return frag;
    }

    /**
     * 显示fragment
     */
    public void showFragment(final BaseFragment frag) {


//        FragmentTransaction tra = fm.beginTransaction();
//        //tra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//
//        tra.replace(R.id.mainContent, frag, frag.getClass().getName());
//        tra.commit();
        loadRootFragment(R.id.mainContent,frag);
    }

    @Override
    public void onCurrentTabChanged(int index) {
        beginIntent(index);
    }

    private void beginIntent(int index){
        StubObject mainMenuItem = mainMenus.get(index);
        String isActivity = mainMenuItem.getString("isActivity","");
        // frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
        if(isActivity.equals("true")){
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<?> clazz = null;
            try {
                List<StubObject> subMenus = Registry.getRegEntryList((String) mainMenuItem.getID());
                Hashtable menuTable = mainMenuItem.getStubTable();
                StubObject stubObject = subMenus.get(0);
                String AndroidShow  = stubObject.getString("AndroidShow","");
                clazz = loader.loadClass(AndroidShow);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if(clazz!=null) {
                startActivity(new Intent(this, clazz));
            }
        }else {
            showFragment(index);
        }
    }

    public void showFragment(int index) {
//        Log.i("", "test-----====================TabBottomActivity: onCurrentTabChanged:位置：" + index);
        // 缓存并显示fragment

        if (cachedFragments[index] != null) { // 取缓存
            willShowFragment = cachedFragments[index];
        } else {
            willShowFragment = initAndCacheFragment(index);

        }
        FragmentTransaction ft = obtainFragmentTransaction(index);
        getCurrentFragment().onPause(); // 暂停当前tab
        if (willShowFragment.isAdded()) {
            willShowFragment.onStart(); // 启动目标tab的onStart()
        } else {
            ft.add(R.id.mainContent, willShowFragment);
        }
//        showTab(index); // 显示目标tab
        // ft.commit();
        //允许状态值丢失，解决一个闪退问题
        ft.commitAllowingStateLoss();
        currentIndex = index;

        tb.setCurrentTabColor(index);
        tb.mCurrentTabIndex = index;

    }

    /**
     * 切换TAB(先隐藏，后显示)
     *
     * @param
     */
    private void showTab(int index) {
        FragmentTransaction ft = obtainFragmentTransaction(index);
        willShowFragment = cachedFragments[index];
        willHideFragment = cachedFragments[currentTab];
        if (willHideFragment != null) {
            ft.hide(willHideFragment);
        }

        if (willShowFragment != null) {
            ft.show(willShowFragment);
            // ft.replace(R.id.mainContent, willShowFragment, willShowFragment.getClass().getName());
        }
        ft.commit();
        currentTab = index; // 更新目标tab为当前tab
    }

    public Fragment getCurrentFragment() {
        return cachedFragments[currentTab];
    }

    /**
     * 获取一个带动画的FragmentTransaction
     *
     * @param index
     * @return
     */
    private FragmentTransaction obtainFragmentTransaction(int index) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        return ft;
    }

    private void initBadge() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, CART_AMOUNT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("goodTotalCount")) {
                        int count = jsonObject.getInt("goodTotalCount");
                        EFImage efImage = tb.getImageList().get(1);
                        if (efImage.getBadgeView() == null) {
                            BadgeView badgeView = new BadgeView(MainMallActivity.this, efImage);
                            badgeView.setBadgeMargin(0, 0);
                            badgeView.setTextSize(13);

                            efImage.initBadgeView(badgeView);
                        }
                        if (count > 0) {
                            efImage.getBadgeView().setVisibility(View.VISIBLE);
                            efImage.setBadgeCount(count);
                        }else {
                            efImage.getBadgeView().setVisibility(View.INVISIBLE);
                        }


                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });

        HashMap<String, String> params = new HashMap<>();
        params.put("status", "all");
        params.put("userId", EnvironmentVariable.getUserName());
        params.put("num", "0");
        params.put("pageSize", "5");
        MallRequestUtil.getRequest(TAG, ORDER_LIST_URL, params, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    Gson gson = new GsonBuilder().serializeNulls().create();
                    OrderList orderList = gson.fromJson(response, OrderList.class);
                    int count = 0;
                    if (orderList.getResult().equals("success") && orderList.getStatusCounts() != null) {
                        for (OrderList.StatusCountsBean statusCountsBean : orderList.getStatusCounts()) {
                            if (statusCountsBean.getPaymentStatus().equals("0")) {
                                count += statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals("1")) {
                                count += statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals("4")) {
                                count += statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals("5")) {
                                count += statusCountsBean.getCount();
                            } else if (statusCountsBean.getPaymentStatus().equals("2")) {
                                count += statusCountsBean.getCount();
                            }
                        }
                    }
                    EFImage efImage = tb.getImageList().get(2);
                    if (efImage.getBadgeView() == null) {
                        BadgeView badgeView = new BadgeView(MainMallActivity.this, efImage);
                        badgeView.setBadgeMargin(0, 0);
                        badgeView.setTextSize(13);

                        efImage.initBadgeView(badgeView);
                    }
                    if (count > 0) {
                        efImage.getBadgeView().setVisibility(View.VISIBLE);
                        efImage.setBadgeCount(count);
                    } else {
                        efImage.getBadgeView().setVisibility(View.INVISIBLE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBottomBar = null;
        EventBus.getDefault().unregister(this);
    }
}
